package org.opens.util;

import com.jcraft.jsch.ChannelExec;
import com.jcraft.jsch.JSch;
import com.jcraft.jsch.JSchException;
import com.jcraft.jsch.Session;

import java.io.InputStream;

/**
 * 功能描述
 *
 * @author: zhangyuming
 * @date: 2024/3/26 10:45
 */
public class JschUtil2 {

    /**
     * 获取命令输出结果
     *
     * @param host     ip信息
     * @param username 用户名
     * @param password 密码
     * @param command  命令
     * @return 命令输出结果
     */
    public static String execCommand(String host, String username, String password, String command) {
        Session session = null;
        ChannelExec channelExec = null;
        StringBuilder resultBuilder = new StringBuilder();

        try {
            JSch jsch = new JSch();
            session = jsch.getSession(username, host, 22);
            session.setPassword(password);

            session.setConfig("StrictHostKeyChecking", "no");
            session.connect();

            channelExec = (ChannelExec) session.openChannel("exec");
            channelExec.setCommand(command);
            channelExec.setInputStream(null);
            InputStream in = channelExec.getInputStream();
            channelExec.connect();

            byte[] tmp = new byte[1024];
            while (true) {
                while (in.available() > 0) {
                    int i = in.read(tmp, 0, 1024);
                    if (i < 0) break;
                    // System.out.print(new String(tmp, 0, i));
                    resultBuilder.append(new String(tmp, 0, i));
                }
                if (channelExec.isClosed()) {
                    if (in.available() > 0) {
                        continue;
                    }
                    // System.out.println("exit-status: " + channelExec.getExitStatus());
                    break;
                }
                // 是为了每秒检查一次远程命令的输出，以确保输出完整。如果你不需要等待，也可以去掉这部分代码，不过请注意如果远程命令输出很快，可能会导致部分输出被错过。
                //try {
                //    Thread.sleep(1000);
                //} catch (Exception ee) {
                //    // pass
                //}
            }

            // System.out.println(resultBuilder.toString());
            return resultBuilder.toString();
        } catch (JSchException | java.io.IOException e) {
            throw new RuntimeException(e);
        } finally {
            // 关闭连接
            if (channelExec != null) {
                channelExec.disconnect();
            }
            if (session != null) {
                session.disconnect();
            }
        }
    }

}
